package cz.khfotbal.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.khfotbal.dao.TeamDao;
import cz.khfotbal.domain.Team;
import cz.khfotbal.domain.User;

@Repository
@Transactional
public class TeamDaoImpl implements TeamDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session session;

	public List<Team> findAllTeams() {
		session = sessionFactory.getCurrentSession();
		List<Team> list = session.createQuery("from Team").list();
		return list;
	}

	public void updateTeam(Team selectedTeam) {
		session = sessionFactory.getCurrentSession();
		session.update(selectedTeam);
	}

	public void saveTeam(Team newTeam) {
		session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(newTeam);
	}

	public void deleteTeam(Team selectedTeam) {
		session = sessionFactory.getCurrentSession();
		session.delete(selectedTeam);
	}

	public Team findTeamByName(String name) {
		session = sessionFactory.getCurrentSession();
		Team team = (Team) session.createQuery(
				"from Team where name='" + name + "'").uniqueResult();
		return team;
	}

	public List<Team> findTeamsByUser(User loggedUser) {
		session = sessionFactory.getCurrentSession();
		List<Team> list = session.createQuery(
				"from Team t where t.user.id=" + loggedUser.getId()).list();
		return list;
	}

}
